package com.guzhi.service.sms.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.guzhi.common.Consts;
import com.guzhi.exception.GZException;
import com.guzhi.service.sms.SmsHandler;
import com.guzhi.utils.CryptUtil;
import com.guzhi.utils.HttpClientHelper;

/**
 * 漫道短信接口
 * 
 * @author duanshao
 * 
 */
public class MDSmsHandler implements SmsHandler {
    private final static Logger LOG = LoggerFactory.getLogger(SmsHandler.class);
    @Value("${sms.md.sn}")
    private String sn;
    @Value("${sms.md.pwd}")
    private String pwd;

    private String host;

    public void setHost(String host) {
        this.host = host;
    }

    private boolean isAlive = true;

    private int failTimes;

    private final String SEND_TEMPLATE = "%s/mdsmssend.ashx?sn=%s&pwd=%s&mobile=%s&content=%s&ext=&stime=&rrid=&msgfmt=";

    @Override
    public int send(String phone, String content) {
        String url = String.format(SEND_TEMPLATE, host, sn, StringUtils.upperCase(CryptUtil.md5(sn + pwd)), phone,
                content);
        LOG.info("send phone:{},content:{},url:{}", phone, content, url);
        String resp = null;
        try {
            resp = HttpClientHelper.sendRequest(url, "utf-8");
        } catch (Exception e) {
            if (e instanceof GZException) {
                GZException ee = (GZException) e;
                if (ee.getCode() == Consts.Code.NET_CONN_ERROR) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e1) {
                    }
                    LOG.info("send retry phone:{}", phone);
                    // 重试一次
                    resp = HttpClientHelper.sendRequest(url, "utf-8");
                }
            }
        }
        LOG.info("send phone:{} response:{}", phone, resp);
        if (StringUtils.isBlank(resp)) {
            return CODE_FAIL;
        }

        if (StringUtils.startsWith(resp, "-")) {
            return CODE_FAIL;
        } else {
            return CODE_SUCCESS;
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.guzhi.service.sms.SmsHandler#isAlive()
     */
    @Override
    public boolean isAlive() {
        return isAlive;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.guzhi.service.sms.SmsHandler#setAlive(boolean)
     */
    @Override
    public void setAlive(boolean isAlive) {
        this.isAlive = isAlive;
        if (isAlive) {
            failTimes = 0;
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.guzhi.service.sms.SmsHandler#addFails()
     */
    @Override
    public void addFails() {
        failTimes++;
        if (failTimes >= 3) {
            setAlive(false);
        }
    }

}
